using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace SimpleFramework
{
    public class FileSystem : TMonoSingletonX<FileSystem>
    {
        private List<Loader> m_AddQueue = new List<Loader>();
        private List<Loader> m_RunQueue = new List<Loader>();


        private void Update()
        {
            if (m_AddQueue.Count > 0 && m_RunQueue.Count < 4)
            {
                m_RunQueue.AddRange(m_AddQueue);
                m_AddQueue.Clear();
            }

            int i = 0;
            while (i < m_RunQueue.Count)
            {
                if (m_RunQueue[i].Update())
                {
                    m_RunQueue.RemoveAt(i);
                }
                else
                {
                    ++i;
                }
            }
        }

        public ILoader LoadFile(
            string url,
            UnityAction<ILoader, byte[]> onComplete,
            UnityAction<ILoader, string> onFailure = null,
            UnityAction<ILoader, float> onProgress = null)
        {
            var loader = BinaryFileLoader.POOL.Spawn();
            loader.Reset();
            loader.Url = url;
            loader.onComplete.AddListener(onComplete);
            if (onProgress != null)
                loader.onProgress.AddListener(onProgress);
            if (onFailure != null)
                loader.onFailure.AddListener(onFailure);
            m_AddQueue.Add(loader);
            return loader;
        }

        public ILoader LoadFile(
            string url,
            UnityAction<ILoader, string> onComplete,
            UnityAction<ILoader, string> onFailure = null,
            UnityAction<ILoader, float> onProgress = null)
        {
            var loader = TextFileLoader.POOL.Spawn();
            loader.Reset();
            loader.Url = url;
            loader.onComplete.AddListener(onComplete);
            if (onProgress != null)
                loader.onProgress.AddListener(onProgress);
            if (onFailure != null)
                loader.onFailure.AddListener(onFailure);
            m_AddQueue.Add(loader);
            return loader;
        }

        public AssetBundleLoader LoadAssetBundle(
            string url,
            UnityAction<ILoader, AssetBundle> onComplete,
            UnityAction<ILoader, string> onFailure = null,
            UnityAction<ILoader, float> onProgress = null)
        {
            var loader = AssetBundleLoader.POOL.Spawn();
            loader.Reset();
            loader.Url = url;
            loader.onComplete.AddListener(onComplete);
            if (onProgress != null)
                loader.onProgress.AddListener(onProgress);
            if (onFailure != null)
                loader.onFailure.AddListener(onFailure);
            m_AddQueue.Add(loader);
            return loader;
        }
    }

}